

package com.hellohoper.script.config.engine.run;

import com.hellohoper.script.config.engine.engine.EngineService;
import com.hellohoper.script.config.engine.run.bean.RunnerParam;
import com.hellohoper.script.config.engine.run.bean.RunnerResult;
import lombok.Getter;
import lombok.Setter;
import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;

import java.util.Map;

/**
 * Groovy执行脚本服务
 * Created by hk on 17/8/15.
 */
@Getter
@Setter
public class GroovyScriptRunnerService<K, V> implements ScriptRunnerService<K, V> {

    private String appName;
    private EngineService engineService;

    @Override
    public RunnerResult run(String appName, String scriptName, RunnerParam runnerParam) throws Exception {
        RunnerResult<K, V> runnerResult = null;
        // 获得脚本对应执行引擎（懒加载方式）
        GroovyScriptEngineImpl groovyEngine = (GroovyScriptEngineImpl) engineService.getGroovyEngine(appName, scriptName);
        if (groovyEngine == null) {
            return runnerResult;
        }
        // 执行脚本
        Map dispatch = (Map) groovyEngine.invokeFunction("dispatch", new Object[]{runnerParam});
        if (dispatch.get("checkError") != null) {
            return RunnerResult.builder()
                    .checkCode(-1)
                    .checkMsg((String) dispatch.get("checkError"))
                    .build();
        }

        return RunnerResult.builder()
                .checkCode(1)
                .runnerResultMap(dispatch)
                .build();
    }

    @Override
    public RunnerResult<K, V> run(String scriptName, RunnerParam runnerParam) throws Exception {
        return this.run(appName, scriptName, runnerParam);
    }
}
